#coding:utf-8
from flask import current_app, jsonify
from ihome.utils.response_code import RET
from ihome.models import Area
from . import api
import json
from ihome import redis_store
from ihome.utils.constains import AREA_CACHE_IN_REDIS_TIME


@api.route('/area', methods=["GET"])
def get_area():
    try:
        resp_json = redis_store.get('area_info')
    except Exception as e:
        current_app.logger.error(e)
    else:
        if resp_json is not None:
            return resp_json, 200, {"Content-Type": "application/json"}

    try:
        areas = Area.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")
    area_list = []
    for area in areas:
        area_list.append(area.to_dict())
    resp_dict = dict(errno=RET.OK, errmsg="OK", data=area_list)
    resp_json = json.dumps(resp_dict)
    try:
        redis_store.setex('area_info', AREA_CACHE_IN_REDIS_TIME, resp_json)
    except Exception as e:
        current_app.logger.error(e)

    return resp_json, 200, {"Content-Type": "application/json"}

